package com.yan.test.work.testpaging3

import android.content.Context
import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.PagingState

class OSCPagingDataSource(val ctx: Context, val keyWord: String) : PagingSource<Int , DataBean>(){
    override fun getRefreshKey(state: PagingState<Int, DataBean>): Int? {
        return state.anchorPosition?.let { position ->
            state.closestPageToPosition(position)?.prevKey?.plus(state.config.pageSize)
                ?: state.closestPageToPosition(position)?.nextKey?.minus(state.config.pageSize)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, DataBean> {
        val from = params.key?:0
        val next = from + params.loadSize
        val queryList = MainCenterApi().queryData(ctx , keyWord , from , params.loadSize)

        return try {
            LoadResult.Page(
                data = queryList,
                prevKey = if(from==0) null else (from - 20) ,
                nextKey = next,
            )
        } catch (e: Exception){
            LoadResult.Error(e)
        }
    }

}
